package com.duoshu.grj.sosoliuda.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.util.Log;

import com.aliyun.demo.recorder.AliyunVideoRecorder;
import com.aliyun.struct.common.ScaleMode;
import com.aliyun.struct.common.VideoQuality;
import com.aliyun.struct.recorder.CameraType;
import com.aliyun.struct.recorder.FlashType;
import com.aliyun.struct.snap.AliyunSnapVideoParam;
import com.duoshu.grj.sosoliuda.Manifest;
import com.duoshu.grj.sosoliuda.SosoRecordActivity;
import com.duoshu.grj.sosoliuda.model.ObjectRequest;
import com.duoshu.grj.sosoliuda.model.bean.AliyunSTSInfoResponse;
import com.duoshu.grj.sosoliuda.model.bean.UserResponse;
import com.duoshu.grj.sosoliuda.model.util.HttpSubscriber;
import com.duoshu.grj.sosoliuda.ui.event.VideoListActivity;
import com.duoshu.grj.sosoliuda.ui.map.MapUtils;
import com.duoshu.grj.sosoliuda.ui.player.PlayerActivity;
import com.duoshu.grj.sosoliuda.upload.AuthInfo;
import com.duoshu.grj.sosoliuda.upload.InvalidAuthInfoException;
import com.duoshu.grj.sosoliuda.upload.SnapVideoUploadAliImp;
import com.duoshu.grj.sosoliuda.upload.SnapVideoUploadApi;
import com.duoshu.grj.sosoliuda.upload.SnapVideoUploadCallback;
import com.duoshu.grj.sosoliuda.upload.SnapVideoUploadManager;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.HashMap;
import java.util.List;

import static android.R.attr.data;

/**
 * 实现短视频的录制上传
 */

public class SnapVideoUtils {
    public static final int REQUEST_RECORD = 2018;


    private static final String[] PERMISSIONS = new String[]{
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * 短视频录制，录制完后的视频路径在onActivityResult中返回
     */
    public static void startRecordForResult(final Activity activity, Bundle bundle) {
        try {

            Acp.getInstance(activity).request(new AcpOptions.Builder().setPermissions(PERMISSIONS).build(), new AcpListener() {
                @Override
                public void onGranted() {

                    int resolutionMode = AliyunSnapVideoParam.RESOLUTION_480P;
                    int ratioMode = AliyunSnapVideoParam.RATIO_MODE_3_4;
                    int maxDuration = 30000;
                    int minDuration = 1000;
                    VideoQuality videoQuality = VideoQuality.HD;
                    int gop = 5;

                    AliyunSnapVideoParam recordParam = new AliyunSnapVideoParam.Builder()
                            //设置录制分辨率，目前支持360p，480p，540p，720p
                            .setResolutionMode(resolutionMode)
                            //设置视频比例，目前支持1:1,3:4,9:16
                            .setRatioMode(ratioMode)
                            //设置录制模式，目前支持按录，点录和混合模式
                            .setRecordMode(AliyunSnapVideoParam.RECORD_MODE_AUTO)
                            //设置滤镜地址列表,具体滤镜接口接收的是一个滤镜数组
//                .setFilterList(eff_dirs)
                            //设置美颜度
                            .setBeautyLevel(80)
                            //设置美颜开关
                            .setBeautyStatus(true)
                            //设置前后置摄像头
                            .setCameraType(CameraType.BACK)
                            //设置闪光灯模式
                            .setFlashType(FlashType.OFF)
                            //设置是否需要支持片段录制
                            .setNeedClip(true)
                            //设置最大录制时长 单位毫秒
                            .setMaxDuration(maxDuration)
                            //设置最小录制时长 单位毫秒
                            .setMinDuration(minDuration)
                            //设置视频质量
                            .setVideoQuality(videoQuality)
                            //设置关键帧间隔
                            .setGop(gop)
                            //设置视频码率，如果不设置则使用视频质量videoQulity参数计算出码率
//                .setVideoBitrate(2000)

                            /**
                             * 裁剪参数
                             */
                            .setMinVideoDuration(4000)
                            .setMaxVideoDuration(29 * 1000)
                            .setMinCropDuration(3000)
                            .setFrameRate(25)
                            .setCropMode(ScaleMode.PS)
                            //设置导入相册过滤选择视频
                            .setSortMode(AliyunSnapVideoParam.SORT_MODE_PHOTO)
                            .build();
                    AliyunVideoRecorder.startRecordForResult(activity, REQUEST_RECORD, recordParam);
                    //           SosoRecordActivity.startRecord(activity, recordParam);


                }

                @Override
                public void onDenied(List<String> permissions) {
                    ToastUtils.toastSingle("拒绝权限无法录制视频~");
                }
            });

        } catch (ActivityNotFoundException | NullPointerException e) {
            Log.e("JumperUtils", e.getMessage());
        }
    }

    /**
     * 上传录制的短视频
     *
     * @param context   上下文
     * @param taskId    上传任务的唯一标识，可用视频路径的md5值
     * @param imgPath   视频封面的路径
     * @param videoPath 视频路径
     */
    public static void upload(final Context context, final String taskId, String imgPath, String videoPath, final SnapVideoUploadCallback callback) {
        final SnapVideoUploadManager manager = SnapVideoUploadManager.getInstance();
        SnapVideoUploadApi snapVideoUploadTask = manager.getUploadTask(taskId);

        try {
            if (snapVideoUploadTask == null) {
                snapVideoUploadTask = new SnapVideoUploadAliImp(imgPath, videoPath);
                LogUtils.d("video", "SnapVideoUtil.upload--新建上传任务---taskid："+taskId+"----------->");
                snapVideoUploadTask.init(context);
            }else{
                LogUtils.d("video", "SnapVideoUtil.upload-获取到已添加的上传任务---taskid："+taskId+"----------->");
            }

            addUploadTask(taskId, callback, manager, snapVideoUploadTask);

        } catch (InvalidAuthInfoException e) {
            //从服务器请求授权信息,设置authInfo

            final SnapVideoUploadApi finalSnapVideoUploadTask = snapVideoUploadTask;
            ObjectRequest.getInstance().getAliCloudAuthInfo().subscribe(new HttpSubscriber<AliyunSTSInfoResponse>() {

                @Override
                public void onNext(AliyunSTSInfoResponse bean) {
                    if (null == bean || null == bean.get_aliyun_sts_info_response || null == bean.get_aliyun_sts_info_response.sts_info) {
                        ToastUtils.toastSingle("获取阿里云上传鉴权信息失败");
                    } else {
                        AliyunSTSInfoResponse.GetAliyunStsInfoResponseBean.StsInfoBean stsInfoBean = bean.get_aliyun_sts_info_response.sts_info;
                        AuthInfo authInfo = new AuthInfo();
                        authInfo.accessKeyId = stsInfoBean.access_key_id;
                        authInfo.accessKeySecret = stsInfoBean.access_key_secret;
                        authInfo.expriedTime = stsInfoBean.expiration;
                        authInfo.securityToken = stsInfoBean.security_token;
                        SnapVideoUploadAliImp.authInfo = authInfo;

                        try {
                            finalSnapVideoUploadTask.init(context);
                            addUploadTask(taskId, callback, manager, finalSnapVideoUploadTask);//重新上传
                        } catch (InvalidAuthInfoException e1) {
                            LogUtils.d("video", "SnapVideoUtil.upload--getAliCloudAuthInfo--上传任务第二次初始化失败-not get sts token--taskid："+taskId+"----------->");
                        } catch(Exception e){
                            LogUtils.d("video", "SnapVideoUtil.upload--getAliCloudAuthInfo--本地错误:"+e.toString()+"---->");
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    LogUtils.d("video", "SnapVideoUtil.upload--getAliCloudAuthInfo--onError-获取阿里云上传鉴权信息失败--taskid："+taskId+"----------->");
                }
            });

        }

    }

    /**
     * 获取视频的首帧图片
     *
     * @param videoFilePath 视频文件路径
     * @return 首帧图片的bitmap
     */
    public static Bitmap getVideoFrame(String videoFilePath) {
        MediaMetadataRetriever mediaRetriever = new MediaMetadataRetriever();
        mediaRetriever.setDataSource(videoFilePath);
        Bitmap bitmap = mediaRetriever.getFrameAtTime();
        mediaRetriever.release();
        return bitmap;
    }

    /**
     * 获取视频的首帧图片的存储路径
     *
     * @param videoFilePath 视频文件路径
     * @return 首帧图片的存储路径
     */
    public static String getVideoFrameImgPath(String videoFilePath) {
        Bitmap bitmap = getVideoFrame(videoFilePath);
        return ImageCropUtils.compressImage(bitmap, String.valueOf(System.currentTimeMillis()) + ".jpg", true, 500);
    }


    private static void addUploadTask(final String taskId, final SnapVideoUploadCallback callback,
                                      final SnapVideoUploadManager manager, SnapVideoUploadApi snapVideoUploadTask) {
        manager.addUploadTask(taskId, snapVideoUploadTask, new SnapVideoUploadCallback() {

            @Override
            public void onUploadSucceed(String videoId, String imageUrl) {
                manager.releaseUploadTask(taskId);
                LogUtils.d("video", "<---SnapVideoUtils--onUploadSucceed--上传任务---taskid："+taskId+"-----videoId:"+videoId+"---imageUrl:"+imageUrl);
                callback.onUploadSucceed(videoId, imageUrl);
            }

            @Override
            public void onUploadFailed(String code, String message) {
                manager.releaseUploadTask(taskId);
                LogUtils.d("video", "<---SnapVideoUtils--onUploadFailed--上传任务---taskid："+taskId+"------errcode:"+code+"---errmessage:"+message+"-->");
                callback.onUploadFailed(code, message);
            }

            @Override
            public void onUploadProgress(long uploadedSize, long totalSize) {
                LogUtils.d("snap-upload-progress", "SnapVideoUtils--onUploadProgress--上传任务---taskid："+taskId+"---uploadsize:"+uploadedSize+"---totalSize:"+totalSize+"----->");
                callback.onUploadProgress(uploadedSize, totalSize);

            }

        });
    }

    /**
     * 播放阿里云视频
     * @param context
     * @param title 视频题目
     * @param video_id 视频id
     */
    public static void playVedio(final Context context, final String title, final String video_id){
            Acp.getInstance(context).request(new AcpOptions.Builder().setPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE).build(), new AcpListener() {
                @Override
                public void onGranted() {
                    Bundle bundle = new Bundle();
                    bundle.putString(PlayerActivity.PLAYER_ID, video_id);
                    bundle.putString(PlayerActivity.PLAYER_TITLE, title);
                    JumperUtils.JumpTo(context, PlayerActivity.class, bundle);
                }

                @Override
                public void onDenied(List<String> permissions) {
                    ToastUtils.toastSingle("拒绝权限无法播放视频~");
                }
            });
        }

    /**
     *计算视频时长
     */
    public static int getVideoDuration(String videoFilePath){
        int duration=0;
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();

        try {
            if (videoFilePath != null) {
//                HashMap<String, String> headers=null;
//                if (headers == null) {
//                    headers = new HashMap<String, String>();
//                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
//                }
                mmr.setDataSource(videoFilePath);
            }

            String strDuration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            duration = Integer.parseInt(strDuration);
            duration= (duration+100)/1000;

        } catch (Exception ex) {
        } finally {
            mmr.release();
        }
        LogUtils.e("video-duration","duration "+duration);
        return duration;
    }
}
